package com.baijiaoxi.common.model.login;

import com.baijiaoxi.common.model.KeyValueManager;
import com.baijiaoxi.common.model.base.CommonError;
import com.baijiaoxi.common.model.base.CoreException;

import java.util.Map;
import java.util.UUID;

public class DefaultLoginHelper implements LoginHelper {
    private Long timeout = 1800L;
    private Map<String, Long> sceneExpire;
    private KeyValueManager keyValueManager;

    public DefaultLoginHelper(KeyValueManager keyValueManager) {
        this.keyValueManager = keyValueManager;
    }

    public DefaultLoginHelper(KeyValueManager keyValueManager, Long timeout) {
        this.keyValueManager = keyValueManager;
        this.timeout = timeout * 60;
    }

    public DefaultLoginHelper(KeyValueManager keyValueManager, Long timeout, Map<String, Long> sceneExpire) {
        this.keyValueManager = keyValueManager;
        this.timeout = timeout * 60;
        this.sceneExpire = sceneExpire;
    }


    private Long getTimeout(String scene) {
        if (sceneExpire != null && sceneExpire.containsKey(scene))
            return sceneExpire.get(scene);
        return timeout;
    }

    private String formatKey(String scene, String userId) {
        return scene + "@@@" + userId;
    }

    private LogonUser fromKey(String key) {
        String[] arr = key.split("@@@", 2);
        return new LogonUser(arr[0], arr[1]);
    }

    @Override
    public String login(String scene, String userId) {
        String sign;
        String key = formatKey(scene, userId);
        if (keyValueManager.hasKey(key)) {
            //登陆过的就删除原登录信息，重新登录
            sign = (String) keyValueManager.get(key);
            keyValueManager.del(sign);
            keyValueManager.del(key);
        }
        //没有登录数据的
        sign = UUID.randomUUID().toString();
        Long timeout = getTimeout(scene);
        keyValueManager.set(sign, key, timeout);
        keyValueManager.set(key, sign, timeout - 60);//先过期
        return sign;
    }


    /**
     * 注销
     *
     * @param scene
     * @param userId
     */
    @Override
    public void layout(String scene, String userId) {
        String key = formatKey(scene, userId);
        if (keyValueManager.hasKey(key)) {
            String sign = (String) keyValueManager.get(key);
            keyValueManager.del(sign);
            keyValueManager.del(key);
        }
    }


    /**
     * 注销
     *
     * @param sign
     */
    public void layout(String sign) {
        if (keyValueManager.hasKey(sign)) {
            String key = (String) keyValueManager.get(sign);
            keyValueManager.del(sign);
            keyValueManager.del(key);
        }
    }


    /**
     * 检查登陆状态
     *
     * @param sign
     * @return
     */
    public boolean checkLogin(String sign) {
        try {
            if (!keyValueManager.hasKey(sign))
                return false;
            String key = (String) keyValueManager.get(sign);
            if (key != null && !key.isEmpty())
                if (!keyValueManager.hasKey(key))
                    return false;
            updateExpire(sign);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 根据sign获取登录用户ID
     *
     * @param sign
     * @return
     */
    public String getUserId(String sign) {
        updateExpire(sign);
        try {
            String key = (String) keyValueManager.get(sign);
            return fromKey(key).getUserId();
        } catch (Exception e) {
            throw CoreException.create(CommonError.dataNotExistOrExpired, e);
        }
    }

    private void updateExpire(String sign) {
        String key;
        try {
            key = (String) keyValueManager.get(sign);
            Long timeout = getTimeout(key);
            keyValueManager.updateExpireTime(sign, timeout);
            if (key != null && !key.isEmpty())
                keyValueManager.updateExpireTime(key, timeout);
        } catch (Exception e) {
            throw CoreException.create(CommonError.dataNotExistOrExpired, e);
        }
        if (key == null || key.isEmpty() || !keyValueManager.hasKey(sign) || !keyValueManager.hasKey(key))
            throw CoreException.create(CommonError.dataNotExistOrExpired);
    }
}
